package com.huchao.www.controller;

import com.github.pagehelper.PageInfo;
import com.huchao.www.exception.MyException;
import com.huchao.www.pojo.AdminInfo;
import com.huchao.www.service.impl.AdminServiceImpl;
import com.huchao.www.utils.LimitUtil;
import com.huchao.www.utils.MD5Util;
import com.huchao.www.vo.UserSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Description:
 * @BelongsProject: springMVC
 * @BelongsPackage: com.huchao.www.controller
 * @Author: 亖思
 * @CreateTime: 2022/11/21 16:23
 * @Version: 1.0
 */

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminServiceImpl adminService;

    @Value("${file-save-path}")
    private String fileSavePath;

    @GetMapping("/add")
    public String adminAdd() {
        return "html/admin-add";
    }

    @GetMapping("/edit/{id}")
    public String adminEdit(@PathVariable("id") Long adminId, Model model) {
        model.addAttribute("admin", adminService.findById(adminId));
        return "html/admin-edit";
    }

    @GetMapping("/del")
    public String adminDel(@RequestParam("id") Long adminId) {
        System.out.println("adminId  " + adminId);
        Date nowDate = new Date();
        adminService.deleteAdmin(adminId, nowDate);
        return "redirect:/admin/list";
    }

    @RequestMapping("/dels")
    public String adminDelMore(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        Date nowDate = new Date();
        adminService.deleteAdmins(list, nowDate);
        return "redirect:/admin/list";
    }

    @RequestMapping("/list")
    public String adminList(UserSearch userSearch,
                            Model model,
                            @RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "4") int size
    ) {

        HashMap<String, Object> map = userSearch.getHashMap();
        List<AdminInfo> adminPageList = adminService.findAdminPageList(map, page, size);
        PageInfo<AdminInfo> adminPageInfo = new PageInfo<>(adminPageList);
        model.addAttribute("pageInfo", adminPageInfo);
        return "html/admin-list";
    }

    @RequestMapping("/doEdit")
    public String adminEdit(String loginName, String phone, String email, MultipartFile profile, String repass, HttpServletRequest req) throws MyException {
        if (!LimitUtil.passwordLimitUtil(repass)) {
            throw new MyException("密码格式错误，密码必须包含大小写字母和数字，长度不能小于8，不能大于16");
        } else {
            System.out.println(loginName + phone + email + repass);
            AdminInfo admin = new AdminInfo();
            admin.setLoginName(loginName);
            admin.setPhone(phone);
            admin.setEmail(email);
            admin.setProfile(fileUpload(profile));
            admin.setPassword(MD5Util.encode(repass + loginName));

            if (adminService.updateAdmin(admin)) {
                return "redirect:/admin/list";
            } else {
                throw new MyException("修改失败");
            }
        }
    }

    @RequestMapping("/doAdd")
    public String save(String username, String phone, String email, MultipartFile profile, String repass, HttpServletRequest req) throws MyException {
        if (!LimitUtil.loginNmaeLimitUtil(username)) {
            throw new MyException("登录名格式错误，登录名只能是大小写字母和数字组合");
        } else if (!LimitUtil.passwordLimitUtil(repass)) {
            throw new MyException("密码格式错误，密码必须包含大小写字母和数字，长度不能小于8，不能大于16");
        } else {
            Date now = new Date();
            AdminInfo admin = new AdminInfo();
            admin.setLoginName(username);
            admin.setPassword(MD5Util.encode(repass + username));
            admin.setEmail(email);
            admin.setPhone(phone);
            admin.setProfile(fileUpload(profile));
            admin.setCreateTime(now);
            adminService.addAdmin(admin);

            return "redirect:/admin/list ";
        }
    }

    /**
     * 〈文件上传--返回文件名〉
     *
     * @param uploadFile:
     * @Author: 亖思
     * @Date: 2023/1/13 17:02
     * @return: String
     **/
    private String fileUpload(MultipartFile uploadFile) {
        if (!uploadFile.isEmpty()) {
            // 如果目录不存在则创建
            File uploadDir = new File(fileSavePath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            //获取原文件名
            String OriginalFilename = uploadFile.getOriginalFilename();
            //获取文件后缀名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
            //重新随机生成名字
            String filename = UUID.randomUUID() + suffixName;
            File localFile = new File(fileSavePath + "\\" + filename);
            try {
                //把上传的文件保存至本地
                uploadFile.transferTo(localFile);
                //上传成功，返回保存的文件地址
                return filename;
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("上传失败");
                return "";
            }
        } else {
            System.out.println("文件为空");
            return "";
        }
    }

}


